<script setup lang="ts">
/**
 * @description 一个通用的图片网格组件，根据传入的 width 和 cols 计算出图片尺寸。
 * mode 为 edit 时，网格尾部显示一个按钮，点击可以从相机或相册中选择照片。
 *
 * @property mode - 在表单中使用此组件时，
 */
const props = defineProps<{
  mode: 'edit' | 'display'
  width: number
  cols: number
  pictures: string[]
}>()

const emit = defineEmits(['pickImage', 'delete'])

const pictureSize = computed(() => (props.width - 25 * (props.cols - 1)) / props.cols)

function handlePreview(index: number, pictures: string[]) {
  uni.previewImage({
    current: index,
    showmenu: true,
    urls: pictures,
    indicator: 'number',
  })
}

function handleDelete(picture: string) {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张图片吗？',
    success: (result) => {
      if (result.confirm)
        emit('delete', picture)
    },
  })
}
</script>

<template>
  <view class="grid gap-25rpx" :style="{ gridTemplateColumns: `repeat(${props.cols}, minmax(0, 1fr))` }">
    <view
      v-for="picture, index in props.pictures"
      :key="index"
      class="relative"
      :style="{ width: `${pictureSize}rpx`, height: `${pictureSize}rpx` }"
    >
      <!-- 图片 Item -->
      <image
        class="rounded-20rpx"
        :style="{ width: `${pictureSize}rpx`, height: `${pictureSize}rpx` }"
        mode="aspectFill"
        :src="picture ? picture : ''"
        @tap="handlePreview(index, pictures)"
      />
      <!-- 右上角删除按钮 -->
      <view
        v-if="props.mode === 'edit'"
        class="absolute h-40rpx w-40rpx flex items-baseline justify-center rounded-32rpx bg-#D3D3D3 -right-20rpx -top-20rpx"
        @tap="() => handleDelete(picture)"
      >
        <view class="text-32rpx text-#333333 leading-36rpx">
          ×
        </view>
      </view>
    </view>
    <!-- 上传照片按钮 -->
    <button
      v-if="mode === 'edit'"
      class="m-0 flex flex-col items-center justify-center border-1px border-#D3D3D3 rounded-10rpx border-solid bg-white p-0"
      hover-class="tapped"
      :style="{ width: `${pictureSize}rpx`, height: `${pictureSize}rpx` }"
      @tap="$emit('pickImage')"
    >
      <image class="h-33rpx w-36rpx" src="@/static/images/camera.png" />
      <Spacer height="20" />
      <view class="text-28rpx text-#999999 leading-28rpx">
        上传照片
      </view>
    </button>
  </view>
</template>

<style scoped>
.tapped {
  background-color: #F8F8F8;
}
</style>
